﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CFE
{
	public static class ProjectReader
	{
		private static void HandleLine(Project proj, string line)
		{
			line = line.Trim();
			if (string.IsNullOrEmpty(line))
				return;

			int index = line.IndexOf(' ');
			if (index == -1)
				return;

			string key = line.Substring(0, index);
			string value = line.Substring(index + 1);

			Project.WorkItem workItem = null;
			if (proj.Items.Any())
				workItem = proj.Items.Last();

			switch (key)
			{
				case "InputFile":
					workItem.InputFilenames.Add(value); break;
				case "OutputFile":
					workItem.OutputFilename = value;break;
				case "SourceMapFilename":
					workItem.SourceMapFilename = value;break;
				case "NewItem":
					proj.AddItem(value);break;
				case "Name":
					proj.Name = value;break;
				
			}
		}
		public static Project ReadFile(string filename)
		{
			filename = Path.GetFullPath(filename);

			

			Project proj = null;

			using (StreamReader sr = new StreamReader(filename))
			{
				proj = new Project(filename);

				Project.WorkItem currentItem = null;

				do
				{
					string line = sr.ReadLine();
					if (line == null)
						break;

					HandleLine(proj, line);
				} while (true);
			}
			return proj;
		}
	}
}
